import time
import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, expenditure_type
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class ExpTypes(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(ExpTypes, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'immeuble': _('Tenement'), 'code': _('Code'), 'name': _('Title') 
                       }

    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        ok_message = ''
        ExpTypeForm = model_form(expenditure_type, exclude=['immeuble', 'lastchange_by'])
            
        if self.request.method == 'GET':
            form = ExpTypeForm()
            
        if self.request.method == 'POST':
            form = ExpTypeForm(self.request.POST)
            
            if form.validate():
                new_exp_type = expenditure_type(
                                                key_name = form['code'].data + "_" + str(imm.key().id()),
                                                immeuble = imm,
                                                code = form['code'].data,
                                                name = form['name'].data,
                                                lastchange_by = self.au
                                                )
                new_exp_type.put()
                while not new_exp_type.is_saved():
                    time.sleep(2)
                ok_message = _('Expenditure type was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        et_id = kwargs.get('et_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return    
        edit_exp_type = expenditure_type.get(et_id)
        if not edit_exp_type: 
            self.redirect(webapp2.uri_for('mainpage'))
            return    
            
        ok_message = ''
        ExpTypeForm = model_form(expenditure_type, exclude=['lastchange_by', 'immeuble'])
            
        if self.request.method == 'GET':
            form = ExpTypeForm(obj = edit_exp_type)
            
        if self.request.method == 'POST':
            form = ExpTypeForm(self.request.POST)
            
            if form.validate():
                form.populate_obj(edit_exp_type)
                edit_exp_type.put()
                ok_message = _('Expenditure type was updated.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
